<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="fetchUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或邮箱"
          style="width: 300px; margin-right: 10px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        
        <el-button @click="resetSearch">
          <el-icon><RefreshLeft /></el-icon>
          重置
        </el-button>
      </div>
      
      <!-- 用户表格 -->
      <el-table
        :data="filteredUsers"
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="{ row }">
            <div class="user-cell">
              <el-avatar :size="32" :src="row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱" min-width="200" />
        
        <el-table-column prop="source" label="注册来源" width="120">
          <template #default="{ row }">
            <el-tag :type="row.source === 'wechat' ? 'success' : 'primary'">
              {{ row.source === 'wechat' ? '微信' : '账号' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewUser(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            
            <el-button type="warning" size="small" @click="editUser(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            
            <el-button type="danger" size="small" @click="deleteUser(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalUsers"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDetailVisible"
      :title="`用户详情 - ${selectedUser?.username}`"
      width="600px"
    >
      <div v-if="selectedUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ selectedUser.id }}
          </el-descriptions-item>
          <el-descriptions-item label="用户名">
            {{ selectedUser.username }}
          </el-descriptions-item>
          <el-descriptions-item label="邮箱">
            {{ selectedUser.email }}
          </el-descriptions-item>
          <el-descriptions-item label="注册来源">
            <el-tag :type="selectedUser.source === 'wechat' ? 'success' : 'primary'">
              {{ selectedUser.source === 'wechat' ? '微信登录' : '账号注册' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDate(selectedUser.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录">
            {{ formatDate(selectedUser.lastLoginAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="userDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editUserVisible"
      title="编辑用户"
      width="500px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editUserVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Refresh,
  Search,
  RefreshLeft,
  User,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getUsers } from '@/api/users'

// 响应式数据
const loading = ref(false)
const users = ref<any[]>([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedUsers = ref<any[]>([])

// 对话框状态
const userDetailVisible = ref(false)
const editUserVisible = ref(false)
const selectedUser = ref<any>(null)
const editLoading = ref(false)

// 表单引用
const editFormRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  status: true
})

// 编辑表单验证规则
const editRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 计算属性
const totalUsers = computed(() => users.value.length)

const filteredUsers = computed(() => {
  if (!searchKeyword.value) {
    return users.value
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return users.value.filter(user => 
    user.username.toLowerCase().includes(keyword) ||
    user.email.toLowerCase().includes(keyword)
  )
})

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    // 这里应该调用真实的 API
    // 暂时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    users.value = [
      {
        id: '1',
        username: 'admin',
        email: 'admin@example.com',
        source: 'local',
        avatar: '',
        createdAt: '2024-01-01T00:00:00Z',
        lastLoginAt: '2024-01-15T10:30:00Z',
        status: true
      },
      {
        id: '2',
        username: 'testuser',
        email: 'test@example.com',
        source: 'local',
        avatar: '',
        createdAt: '2024-01-10T00:00:00Z',
        lastLoginAt: '2024-01-14T15:20:00Z',
        status: true
      },
      {
        id: '3',
        username: '微信用户',
        email: 'wechat@example.com',
        source: 'wechat',
        avatar: '',
        createdAt: '2024-01-12T00:00:00Z',
        lastLoginAt: '2024-01-15T09:15:00Z',
        status: true
      }
    ]
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

// 选择变化处理
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

// 查看用户
const viewUser = (user: any) => {
  selectedUser.value = user
  userDetailVisible.value = true
}

// 编辑用户
const editUser = (user: any) => {
  selectedUser.value = user
  Object.assign(editForm, {
    id: user.id,
    username: user.username,
    email: user.email,
    status: user.status
  })
  editUserVisible.value = true
}

// 删除用户
const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用删除用户的 API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('用户删除成功')
    fetchUsers()
  } catch {
    // 用户取消删除
  }
}

// 重置编辑表单
const resetEditForm = () => {
  Object.assign(editForm, {
    id: '',
    username: '',
    email: '',
    status: true
  })
  editFormRef.value?.resetFields()
}

// 处理编辑提交
const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // 这里应该调用更新用户的 API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('用户信息更新成功')
    editUserVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('更新用户失败:', error)
  } finally {
    editLoading.value = false
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString()
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.users-container {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-cell {
  display: flex;
  align-items: center;
}

.user-cell .username {
  margin-left: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-detail {
  padding: 20px 0;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: #666;
}
</style>
